package bll

import (
	"context"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"

	"manager/auth"
)

type transferRecode struct {
	iTransferRecode store.ITransferRecode
}

var TransferRecode = &transferRecode{
	iTransferRecode: postgres.TransferRecode,
}

func (a *transferRecode) init() func() {
	return func() {}
}

func (a *transferRecode) onEvent(*event.Data) {}

// Create 创建
func (a *transferRecode) Create(ctx context.Context, in *model.TransferRecodeCreateRequest) error {
	var (
		err error
	)

	// 获取用户Id
	in.UserId, _ = auth.ContextUserID(ctx)

	// 构建创建现场数据
	c := buildTransferRecode(in)
	_, err = a.iTransferRecode.Create(ctx, c)
	return err
}

// Update 更新
func (a *transferRecode) Update(ctx context.Context, in *model.TransferRecodeUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	if in.UserId != nil {
		dict["user_id"] = in.UserId
	}

	if in.BindPhones != nil {
		dict["bind_phones"] = in.BindPhones
	}

	if in.EbikeId != nil {
		dict["ebike_id"] = in.EbikeId
	}

	if in.Status != nil {
		dict["status"] = in.Status
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	return a.iTransferRecode.Update(ctx, in.Id, dict)
}

// Delete 删除
func (a *transferRecode) Delete(ctx context.Context, in *model.TransferRecodeDeleteRequest) error {
	return a.iTransferRecode.Delete(ctx, in.Id)
}

// List 列表查询
func (a *transferRecode) List(ctx context.Context, in *model.TransferRecodeListRequest) (*model.TransferRecodeListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.TransferRecode
		out   = &model.TransferRecodeListResponse{}
	)

	if total, list, err = a.iTransferRecode.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.TransferRecodesEntityToDto(list)

	return out, nil
}

// Find 列表查询
func (a *transferRecode) Find(ctx context.Context, in *model.TransferRecodeInfoRequest) (*model.TransferRecodeInfo, error) {
	var (
		err  error
		data *entity.TransferRecode
		out  = &model.TransferRecodeInfo{}
	)

	if data, err = a.iTransferRecode.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.TransferRecodeEntityToDto(data)
	return out, nil
}

// buildTransferRecode 构建创建数据现场
func buildTransferRecode(in *model.TransferRecodeCreateRequest) *entity.TransferRecode {
	// todo: check the entity is required
	return &entity.TransferRecode{

		UserId: in.UserId,

		BindPhones: in.BindPhones,

		EbikeId: in.EbikeId,

		Status: in.Status,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
